import os
import json
from typing import Dict, Any
from pathlib import Path
from .path_manager import path_manager

class Config:
    def __init__(self):
        # 使用路径管理器获取配置文件路径
        self.config_file = path_manager.get_config_file("config.json")
        
        # 默认配置使用相对路径，运行时会被路径管理器转换为正确的绝对路径
        self.default_config = {
            "api_port": 58501,
            "api_host": "127.0.0.1",
            "cors_origins": ["*"],  # 跨域允许的源地址，默认允许所有
            "database_path": str(path_manager.get_database_file()),
            "default_plates": [
                {"name": "AGV1", "capacity": 10},
                {"name": "AGV2", "capacity": 10}, 
                {"name": "TB1", "capacity": 8},
                {"name": "FL1", "capacity": 15}
            ]
        }
        self.load_config()
    
    def load_config(self):
        """加载配置文件"""
        if self.config_file.exists():
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    self.config = json.load(f)
                    
                # 合并默认配置，确保新增的配置项存在
                for key, value in self.default_config.items():
                    if key not in self.config:
                        self.config[key] = value
                        
                # 确保数据库路径是绝对路径
                if "database_path" in self.config:
                    db_path = Path(self.config["database_path"])
                    if not db_path.is_absolute():
                        # 相对路径转换为基于应用目录的绝对路径
                        self.config["database_path"] = str(path_manager.app_dir / db_path)
                        
            except Exception as e:
                print(f"加载配置文件失败: {e}")
                self.config = self.default_config.copy()
        else:
            self.config = self.default_config.copy()
            self.save_config()
    
    def save_config(self):
        """保存配置文件"""
        try:
            # 确保配置目录存在
            self.config_file.parent.mkdir(parents=True, exist_ok=True)
            
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, indent=2, ensure_ascii=False)
        except Exception as e:
            print(f"保存配置文件失败: {e}")
    
    def get(self, key: str, default=None):
        """获取配置值"""
        return self.config.get(key, default)
    
    def set(self, key: str, value: Any):
        """设置配置值"""
        self.config[key] = value
        self.save_config()
    
    @property
    def api_port(self) -> int:
        return self.config.get("api_port", 58501)
    
    @property
    def api_host(self) -> str:
        return self.config.get("api_host", "127.0.0.1")
    
    @property
    def cors_origins(self) -> list:
        """获取跨域允许的源地址列表"""
        return self.config.get("cors_origins", ["*"])
    
    @property
    def database_path(self) -> str:
        """获取数据库路径，确保返回正确的绝对路径"""
        db_path = self.config.get("database_path")
        if db_path:
            path = Path(db_path)
            if path.is_absolute():
                return str(path)
            else:
                # 相对路径转换为绝对路径
                return str(path_manager.app_dir / path)
        else:
            # 使用默认路径
            return str(path_manager.get_database_file())

# 全局配置实例
config = Config() 